package com.group.itms.routes.utils;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.DisplayMetrics;

import com.actionbarsherlock.app.ActionBar;
import com.group.itms.routes.activities.BaseActivity;

public class BitmapUtils {

	public static Bitmap decodeFile(String path, int width, int height) {
		try {
			return decodeStream(new FileInputStream(path), width, height);
		} catch (FileNotFoundException e) {
			return null;
		}
	}
	
	public static Bitmap fitToActivity(BaseActivity activity, int resId) {
		DisplayMetrics dm = new DisplayMetrics(); 
		activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
		int w = dm.widthPixels;
		int h = dm.heightPixels;
		ActionBar ab = activity.getSupportActionBar();
		if (ab != null && ab.isShowing()) {
			h -= ab.getHeight();
		}
		return decodeResource(activity.getResources(), resId, w, h);
	}	
	
	public static Bitmap decodeResource(Resources res, int resId, int width, int height) {
		InputStream in = res.openRawResource(resId);
		return decodeStream(in, width, height);
	}

	public static Bitmap decodeByteArray(byte[] arr, int width, int height) {
		if (arr == null) {
			return null;
		}
		return decodeStream(new ByteArrayInputStream(arr), width, height);
	}
	
	public static Bitmap decodeStream(InputStream in, int width, int height) {
		BitmapFactory.Options opts = new BitmapFactory.Options();
		opts.inSampleSize = calculateSampleSize(in, width, height);
		return BitmapFactory.decodeStream(in, null, opts);
	}
	
	private static int calculateSampleSize(InputStream in, int reqW, int reqH) {
		BitmapFactory.Options opts = new BitmapFactory.Options();
		opts.inJustDecodeBounds = true;
		BitmapFactory.decodeStream(in, null, opts);
		int w = opts.outWidth;
		int h = opts.outHeight;
		if (reqW <= w && reqH <= h) {
			float wRatio = (float) w / reqW;
			float hRatio = (float) h / reqH;
			float ratio = Math.min(wRatio, hRatio);
			return Math.max(Math.round(ratio), 1);
		}
		return 1;
	}
	
}
